//
//  ChatCustomEmotionLeftCell.swift
//  Tinsecret_TW
//
//  Created by wanghui on 2018/11/23.
//  Copyright © 2018年 tst. All rights reserved.
//

import UIKit
import Kingfisher

class ChatCustomEmotionLeftCell: ChatBaseCell {
    
    @IBOutlet weak var imgtopConstraint: NSLayoutConstraint!
    @IBOutlet weak var bgtopConstraint: NSLayoutConstraint!
    @IBOutlet weak var avatar: UIImageView!
    @IBOutlet weak var createTimelabel: WHLabel!
    @IBOutlet weak var namelabel: UILabel!
    @IBOutlet weak var pic: UIImageView!
    
    @IBOutlet weak var activityindicator: UIActivityIndicatorView!
    @IBOutlet weak var sendfailureBtn: UIButton!
    @IBOutlet weak var picWidthContraint: NSLayoutConstraint!
    @IBOutlet weak var picHeightContraint: NSLayoutConstraint!
    
    @IBOutlet weak var avatarWiConstraint: NSLayoutConstraint!
    @IBOutlet weak var avatarHeiConstraint: NSLayoutConstraint!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        self.pic.isUserInteractionEnabled = true
        self.addLongPress()
        
        self.selectionStyle = UITableViewCell.SelectionStyle.none
        self.pic.isUserInteractionEnabled = true
        self.pic.clipsToBounds = true
        self.pic.layer.cornerRadius = 5;
        
        //      let tap = UITapGestureRecognizer(target: self, action: #selector(pictap))
        //      pic?.addGestureRecognizer(tap)
        
        self.avatar.isUserInteractionEnabled = true
        let tapAvatar = UITapGestureRecognizer.init(target: self, action: #selector(tapSelector))
        self.avatar.addGestureRecognizer(tapAvatar)
        
        let tapPic = UITapGestureRecognizer.init(target: self, action: #selector(tapPicture))
        self.pic.addGestureRecognizer(tapPic)
        
        let resend = UITapGestureRecognizer.init(target: self, action: #selector(resendMsg))
        self.sendfailureBtn.addGestureRecognizer(resend)
        
        self.createTimelabel.paddingLeft = 5
        self.createTimelabel.paddingRight = 5
        self.createTimelabel.layer.cornerRadius = 5
        self.createTimelabel.layer.masksToBounds = true
        self.avatarAddLongPress() //头像添加长按
    }
    
    @objc func tapSelector() {
        print("点击了头像")
    }
    
    
    //长按头像实现@功能
    @objc func avatarAddLongPress() {
        let longPressGes = UILongPressGestureRecognizer.init(target: self, action: #selector(avatarLongPress(_:)))
        longPressGes.minimumPressDuration = 0.5
        
        longPressGes.allowableMovement = 30
        self.avatar.isUserInteractionEnabled = true
        self.avatar.addGestureRecognizer(longPressGes)
    }
    
    @objc func avatarLongPress(_ longPressGest:UILongPressGestureRecognizer) {
        if longPressGest.state == UIGestureRecognizer.State.began {
            //长按手势添加@
            self.delegate?.addAtInTextviewDelegate(msg: model)
        }else {
            
        }
    }
    
    @objc func tapPicture() {
        let objDic = ["model": model, "view": self.pic] as [String : Any]
        delegate?.openEmotion(objDic)
    }
    @objc func resendMsg() {
        self.model.status = .pending
        self.layoutSubviews()
        self.delegate?.resend(self.model,cell:self)
    }


    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    
    override func setup(model: ChatMessage) {
        super.setup(model: model)
        if let avatar = model.avatar {
            self.avatar.kf.setImage(with: KF.ImageResource(downloadURL: Common.avatarUrl(avatar) ?? URL(string: "localhost")!), placeholder: #imageLiteral(resourceName: "timg"))
        } else {
            self.avatar.image = #imageLiteral(resourceName: "timg")
        }
        
      
        var url = Common.getLocalUrl(model.stickerPath ?? "", file: "emotionUrl")
        if  !FileManager.default.fileExists(atPath: url.path) {
            let remoteUrl = Common.stickerUrl(model.stickerPath!)!
            FileDownloadTool.instance.download(remoteUrl, to: url)
            url = remoteUrl
        }
        self.pic.kf.indicatorType = .activity
        self.pic.kf.setImage(with: url, placeholder: UIImage.init(named: ""))
        
//        if let url = Common.getLocalUrl(model.imgPath!, file: "emotionUrl"){
//            let url = Common.getLocalUrl(model.imgPath!, file: "emotionUrl")
//            self.pic.kf.setImage(with: url, placeholder: UIImage.init(named: "center_image"))
//        }else {
//
//        }

        
//        let size = Common.getImgSize(model.imgSize!)
        self.picWidthContraint.constant = 125
        self.picHeightContraint.constant = 125
        self.createTimelabel.isHidden = !model.showTimeLabel
        self.createTimelabel.text = model.timeStr
        self.namelabel.text = model.fromName
        self.imgtopConstraint.constant = self.createTimelabel.isHidden == true ? 8: 40
        if model.status == .pending {
            self.activityindicator.isHidden = false
            self.activityindicator.startAnimating()
        } else {
            self.activityindicator.isHidden = true
            self.activityindicator.stopAnimating()
        }
        self.sendfailureBtn.isHidden = !(model.status == .error)
        
//        self.createTimelabel.backgroundColor = model.timeBGMode ? UIColor.white.withAlphaComponent(0.5) : UIColor.black.withAlphaComponent(0.15)
//        self.createTimelabel.textColor = model.timeBGMode ? UIColor.black : UIColor.white
        
//        if (UserDefaults.standard.object(forKey: fontCoefficient) != nil) {
//            let contentfontSize = self.getContentFont()
//            let timeFontSize = self.getTimeFont()
//            self.createTimelabel.font = UIFont.systemFont(ofSize: timeFontSize)
//            self.namelabel.font = UIFont.systemFont(ofSize: timeFontSize)
//            self.avatarWiConstraint.constant = self.getAvatarWidth()
//            self.avatarHeiConstraint.constant = self.getAvatarWidth()
//        }
    }
    
    override func updateUI() {
        super.updateUI()
        DispatchQueue.main.async {
            if self.model.status == .pending {
                self.activityindicator.isHidden = false
                self.activityindicator.startAnimating()
            } else {
                self.activityindicator.isHidden = true
                self.activityindicator.stopAnimating()
            }
            self.sendfailureBtn.isHidden = !(self.model.status == .error)
        }
    }
    
}


extension ChatCustomEmotionLeftCell {
    
//    func getContentFont() ->CGFloat {
//        var fontSize:CGFloat = UserDefaults.standard.object(forKey: fontCoefficient) as! CGFloat
//        switch fontSize {
//        case 1:
//            fontSize = 15
//        case 2:
//            fontSize = 16
//        case 3:
//            fontSize = 18
//        case 4:
//            fontSize = 20
//        case 5:
//            fontSize = 22
//        case 6:
//            fontSize = 26
//        default:
//            fontSize = 16
//        }
//        return fontSize
//    }
//    
//    func getTimeFont() ->CGFloat {
//        var fontSize:CGFloat = UserDefaults.standard.object(forKey: fontCoefficient) as! CGFloat
//        switch fontSize {
//        case 1:
//            fontSize = 12
//        case 2:
//            fontSize = 12
//        case 3:
//            fontSize = 13
//        case 4:
//            fontSize = 14
//        case 5:
//            fontSize = 14
//        case 6:
//            fontSize = 14
//        default:
//            fontSize = 16
//        }
//        return fontSize
//    }
//    
//    func getAvatarWidth() -> CGFloat {
//        var fontCoeffi:CGFloat = UserDefaults.standard.object(forKey: fontCoefficient) as! CGFloat
//        switch fontCoeffi {
//        case 1:
//            fontCoeffi = 37
//        case 2:
//            fontCoeffi = 40
//        case 3:
//            fontCoeffi = 41
//        case 4:
//            fontCoeffi = 41
//        case 5:
//            fontCoeffi = 46
//        case 6:
//            fontCoeffi = 51
//        default:
//            fontCoeffi = 41
//        }
//        return fontCoeffi
//    }
//    
    //长按手势
    @objc func addLongPress() {
        let longPressGes = UILongPressGestureRecognizer.init(target: self, action: #selector(longPressView(_:)))
        //长按等待时间
        longPressGes.minimumPressDuration = 0.5
        
        //长按时候,手指头可以移动的距离
        longPressGes.allowableMovement = 30
        self.pic.addGestureRecognizer(longPressGes)
    }
    
    @objc func longPressView(_ longPressGest:UILongPressGestureRecognizer) {
        if longPressGest.state == UIGestureRecognizer.State.began {
            //长按手势开启
            self.addMenuItem()
        }else {
            
        }
    }
    
    func addMenuItem() {
        self.becomeFirstResponder()
        
        let addEmotionItem = UIMenuItem.init(title: NSLocalizedString("添加表情",comment:"添加表情"), action: #selector(addToFavouriteEmotions))
        let zhuanfa = UIMenuItem.init(title: NSLocalizedString("转发",comment:"转发"), action: #selector(zhuanfaAction))
        let report = UIMenuItem.init(title: NSLocalizedString("举报",comment:"举报"), action: #selector(reportAction))
        let menuVC = UIMenuController.shared
        menuVC.menuItems = [addEmotionItem, zhuanfa, report]
        
        
        //长按手势结束
        menuVC.setTargetRect(CGRect.init(x: (self.pic.frame.origin.x + self.pic.frame.size.width * 0.5), y: self.pic.frame.origin.y, width: 0, height: 0), in: self)
        menuVC.setMenuVisible(true, animated: true)
        print("长按触发")
        
    }
    
    override var canBecomeFirstResponder: Bool {
        return true
    }
    
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        
        //            action == #selector(zhuanfaAction){
        //            return true
        //        }else if
        //         if   action == #selector(delete){
        //            return true
        //        }else if action == #selector(reportAction){
        //            return true
        //        }
        
        if (action == #selector(delete) || action == #selector(reportAction) || action == #selector(zhuanfaAction) || action == #selector(addToFavouriteEmotions)){
            return true
        }
        return false
    }
    //添加到表情
    @objc func addToFavouriteEmotions(_ sender: Any?) {
        print("添加到表情")
        //添加到表情
        self.delegate?.addToFavouriteEmotions(msg:model)
    }
    
    //删除
    @objc override func delete(_ sender: Any?) {
        print("删除")
        //删除
        self.delegate?.deleteDelegate(msg:model)
    }
    //举报
    @objc func reportAction() {
        print("举报")
        //举报
        self.delegate?.reportDelegate(msg:model)
    }
    //转发
    @objc func zhuanfaAction() {
        self.delegate?.zhuanfaDelegate(msg: model)
    }
}
